// Lottery2.cpp : Defines the class behaviors for the application.
//

#include "stdafx.h"
#include "Lottery2.h"
#include "MainFrm.h"

#include "ChildFrm.h"
#include "Lottery2Doc.h"
#include "Lottery2View.h"

#include "config.h"

#include <boost/date_time/posix_time/posix_time_types.hpp>
//#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>
// #include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/support/date_time.hpp>
#include <fstream>
#include <boost/log/core.hpp>
#include <boost/log/sinks/sync_frontend.hpp>
#include <boost/log/sinks/text_ostream_backend.hpp>
#include <boost/log/sinks/debug_output_backend.hpp>

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CLottery2App

BEGIN_MESSAGE_MAP(CLottery2App, CWinApp)
	ON_COMMAND(ID_APP_ABOUT, &CLottery2App::OnAppAbout)
	// Standard file based document commands
	ON_COMMAND(ID_FILE_NEW, &CLottery2App::OnFileNew)
// 	ON_COMMAND(ID_FILE_OPEN, &CWinApp::OnFileOpen)
END_MESSAGE_MAP()


// CLottery2App construction

CLottery2App::CLottery2App()
{
	// TODO: add construction code here,
	// Place all significant initialization in InitInstance

	init_log();
	LOG << "====lottery app lauched!====";

}


// The one and only CLottery2App object

CLottery2App theApp;


// CLottery2App initialization

BOOL CLottery2App::InitInstance()
{
	// InitCommonControlsEx() is required on Windows XP if an application
	// manifest specifies use of ComCtl32.dll version 6 or later to enable
	// visual styles.  Otherwise, any window creation will fail.
	INITCOMMONCONTROLSEX InitCtrls;
	InitCtrls.dwSize = sizeof(InitCtrls);
	// Set this to include all the common control classes you want to use
	// in your application.
	InitCtrls.dwICC = ICC_WIN95_CLASSES;
	InitCommonControlsEx(&InitCtrls);

	CWinApp::InitInstance();

	// Initialize OLE libraries
	if (!AfxOleInit())
	{
		AfxMessageBox(IDP_OLE_INIT_FAILED);
		return FALSE;
	}

	// Standard initialization
	// If you are not using these features and wish to reduce the size
	// of your final executable, you should remove from the following
	// the specific initialization routines you do not need
	// Change the registry key under which our settings are stored
	// TODO: You should modify this string to be something appropriate
	// such as the name of your company or organization
	SetRegistryKey(_T("Local AppWizard-Generated Applications"));
	LoadStdProfileSettings(0);  // Load standard INI file options (including MRU)
	// Register the application's document templates.  Document templates
	//  serve as the connection between documents, frame windows and views
	CMultiDocTemplate* pDocTemplate;
	pDocTemplate = new CMultiDocTemplate(IDR_Lottery2TYPE,
		RUNTIME_CLASS(CLottery2Doc),
		RUNTIME_CLASS(CChildFrame), // custom MDI child frame
		RUNTIME_CLASS(CLottery2View));
	if (!pDocTemplate)
		return FALSE;
	AddDocTemplate(pDocTemplate);

	// create main MDI Frame window
	CMainFrame* pMainFrame = new CMainFrame;
	if (!pMainFrame || !pMainFrame->LoadFrame(IDR_MAINFRAME))
	{
		delete pMainFrame;
		return FALSE;
	}
	m_pMainWnd = pMainFrame;
	// call DragAcceptFiles only if there's a suffix
	//  In an MDI app, this should occur immediately after setting m_pMainWnd


	// Parse command line for standard shell commands, DDE, file open
	CCommandLineInfo cmdInfo;
	ParseCommandLine(cmdInfo);


	// Dispatch commands specified on the command line.  Will return FALSE if
	// app was launched with /RegServer, /Register, /Unregserver or /Unregister.
	if (!ProcessShellCommand(cmdInfo))
		return FALSE;
	// The main window has been initialized, so show and update it
	pMainFrame->ShowWindow(SW_SHOWMAXIMIZED);
	pMainFrame->UpdateWindow();

	

	

	return TRUE;
}

 int CLottery2App::ExitInstance()
 {
	 
	 //
	 return CWinApp::ExitInstance();
 }


// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };

protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()

// App command to run the dialog
void CLottery2App::OnAppAbout()
{
	CAboutDlg aboutDlg;
	aboutDlg.DoModal();
}


// CLottery2App message handlers


void CLottery2App::CheckStart()
{
// 	boost::asio::io_service io;
// 	std::string url="http://bf.bet007.com/vbsxml/bfdata.js";
// 	//http://bf.bet007.com/vbsxml/bfdata.js
// 	//http://info.310win.com/jsData/leftData/leftData.js
// 	//http://bf.bet007.com/Over_matchdate.aspx?matchdate=%Y-%m-%d&Submit=%%B2%%E9%%D1%%AF&team=&sclass=
// 	//http://1x2.nowscore.com/%s.js


	//1
// (
// 	boost::shared_ptr<downloader> d(new downloader(io,m_pMainWnd));
// 	d->start(url);
// 	io.run();
// )

	//2
// 	avhttp::multi_download d(io);
// 	avhttp::settings s;
// 	s.check_certificate = false;
// 	d.start(url, s);


}

void CLottery2App::init_log()
{
	namespace logging = boost::log;
	namespace expr = boost::log::expressions;
	namespace sinks = boost::log::sinks;

	CString strLog=COleDateTime::GetCurrentTime().Format("../log/%Y_%m_%d.log");
	namespace fs = boost::filesystem;
	fs::path pth((LPCTSTR)strLog);
	if (!fs::exists(pth.branch_path()))
		fs::create_directories(pth.branch_path());

	typedef sinks::synchronous_sink< sinks::text_ostream_backend > text_sink;
	boost::shared_ptr< text_sink > sink = boost::make_shared< text_sink >();
	sink->set_formatter(
		expr::format("%1%: %2%") 
		% expr::format_date_time< boost::posix_time::ptime >("TimeStamp", "%H:%M:%S") 
		% expr::smessage
		);
	sink->locked_backend()->add_stream(
		boost::make_shared< std::ofstream >(pth.c_str(),std::ios_base::app));
	logging::core::get()->add_sink(sink);

#ifdef _DEBUG

	typedef sinks::synchronous_sink< sinks::debug_output_backend > debug_sink;
	boost::shared_ptr< debug_sink > sink_d = boost::make_shared< debug_sink >();
	sink_d->set_filter(expr::is_debugger_present());
	sink_d->set_formatter(
		expr::format("%1%: %2%\n") 
		% expr::format_date_time< boost::posix_time::ptime >("TimeStamp", "%H:%M:%S") 
		% expr::smessage
		);
	logging::core::get()->add_sink(sink_d);

#endif

// 	logging::add_file_log(
// 		keywords::file_name = "../log/%Y_%m_%d.log",
// 		keywords::format = 
// 		(
// 		expr::stream
// 		<< expr::format_date_time< boost::posix_time::ptime >("TimeStamp", "%H:%M:%S")
// 		<< ": " << expr::smessage
// 		)
// 		);

	logging::add_common_attributes();
	
}

void CLottery2App::OnFileNew()
{
	OpenMatch(0,FALSE);
}

void CLottery2App::OpenMatch(int id,BOOL bNew/*=FALSE*/)
{
	BOOL bExist=FALSE;
 	m_sigOpenM(id,bNew,bExist);
	if (bExist)
		return;
	//open a new match
	((CMainFrame*)m_pMainWnd)->SetNewTabLeft(!bNew);
	POSITION pos=GetFirstDocTemplatePosition();
	CDocTemplate* pTemplate = GetNextDocTemplate(pos);
	CLottery2Doc* pDoc=(CLottery2Doc*)CLottery2Doc::CreateObject();
	pTemplate->AddDocument(pDoc);
	pDoc->SetMatch(id,bNew);
	pDoc->m_cntMatch=m_sigOpenM.connect(bNew?0:1,boost::bind(&CLottery2Doc::onMatch,pDoc,_1,_2,_3));

	CCreateContext context;
	context.m_pCurrentFrame = (CFrameWnd*)m_pMainWnd;
	context.m_pCurrentDoc	= pDoc;
	context.m_pNewViewClass = RUNTIME_CLASS(CLottery2View);
	context.m_pNewDocTemplate = pTemplate;

	CFrameWnd* pFrame = (CFrameWnd*)CChildFrame::CreateObject();
	if (pFrame == NULL)
	{
		TRACE0("Warning: Dynamic create of frame  failed.\n");
		return ;
	}
	ASSERT_KINDOF(CFrameWnd, pFrame);

	if (!pFrame->LoadFrame(IDR_Lottery2TYPE,WS_OVERLAPPEDWINDOW,NULL, &context))
	{
		TRACE0("Warning: CDocTemplate couldn't create a frame.\n");
		// frame will be deleted in PostNcDestroy cleanup
		return ;
	}
	pTemplate->InitialUpdateFrame(pFrame,NULL);
}